package day18;

public class Demo7 {
    public static void main(String[] args) {
        Demo7 d1 = new Demo7();
        Demo7 d2 = new Demo7();
        //线程1:先添加d1的锁  再添加d2的锁
        new Thread(()->{
            synchronized (d1) {
                System.out.println("线程1获取d1的锁，等待获取d2的锁");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (d2) {
                    System.out.println("线程1获取了d1的锁，也获取d2的锁");
                }
                System.out.println("线程1释放了d2的锁");
            }
            System.out.println("线程1释放了d1的锁");
        }).start();

        new Thread(()->{
            synchronized (d2) {
                System.out.println("线程2获取d2的锁，等待获取d1的锁");
                synchronized (d1) {
                    System.out.println("线程1获取了d1的锁，也获取d2的锁");
                }
                System.out.println("线程1释放了d1的锁");
            }
            System.out.println("线程1释放了d2的锁");
        }).start();
    }
}
